package com.aqsare;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.dukascopy.api.*;

import nl.chess.it.util.config.ConfigValidationResult;

import SQLite.Backup;
import SQLite.Blob;
import SQLite.Stmt;
import au.com.bytecode.opencsv.CSVReader;

public class nextpattern {
	 

	private static SimpleConfig config = new SimpleConfig(
			SimpleConfig.RESOURCE_NAME);
	private ArrayList<candle>[] my_period = new ArrayList[config.getPeriod().length];
	private ArrayList<pattern>[] my_pattern = new ArrayList[config.getPeriod().length];
	private ArrayList<indicator>[] my_sma = new ArrayList[config.getPeriod().length];
	private int trend[] = new int[config.getPeriod().length];
	private long last_time[] = new long[config.getPeriod().length];
	private int max_patts[] = new int[config.getPeriod().length];
	private pattern now_patt[] = new pattern[config.getPeriod().length];
	private CalcNowPatt now_patt_v2 = new CalcNowPatt(
			config.getPeriod().length, config.getNowPoints());
	private ArrayList<pattern>[] my_win_pattern = new ArrayList[config
			.getPeriod().length];
	private ArrayList<order> my_orders;
	private SMA now_sma1;
	private int count_max;
	private int now_trend[] = new int[config.getPeriod().length];;
	private String Instrument;
	private double MAX_spike[] = new double[config.getPeriod().length];
	MinimalDynamicChart my_plot;

	public nextpattern() {
		// getConfig();
		now_sma1 = new SMA(config.getSMA1());
		for (int i = 0; i < config.getPeriod().length; i++) {

			my_period[i] = new ArrayList<candle>();
			my_period[i].add(new candle(0, 0, 0, 0, 0, 0, 0));

			my_pattern[i] = new ArrayList<pattern>();
			my_win_pattern[i] = new ArrayList<pattern>();
			my_sma[i] = new ArrayList<indicator>();
			my_sma[i].add(new indicator(0, 1, 0,0));
			trend[i] = 0;
			max_patts[i] = 0;
			now_trend[i] = 0;
			now_patt[i] = new pattern(0);
			MAX_spike[i] = 0;
			last_time[i] = 0;
		}
	//	my_plot = new MinimalDynamicChart();
		count_max = 0;

		my_orders = new ArrayList<order>();
	}

	public void setInstrument(String Instr) {
		this.Instrument = Instr;

	}

	public void loadData() {
		for (int i = 0; i < config.getPeriod().length; i++) {
			count_max = 0;
			getData(i,
					config.getPathCsv() + config.getCurrency()
							+ config.getPeriod()[i] + ".csv");

		}

	}

	public void loadPatt() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			getListPattern(i);

		}

	}

	private int getMinMax(int my_list_no, double now_val) {
		int max = 0;
		double variatie = my_sma[my_list_no].get(my_sma[my_list_no].size() - 1)
				.getVal() - now_val;

		if (variatie == 0) { // /nu e variatie, setam la asta ce avea
								// precedentul si la precedentul 0
			max = my_sma[my_list_no].get(my_sma[my_list_no].size() - 1)
					.getMax();
			my_sma[my_list_no].get(my_sma[my_list_no].size() - 1).setMax(0);
		} else if (variatie > 0) { // trend descendent
			max = -1;
			now_trend[my_list_no] = -1;
			if (my_sma[my_list_no].get(my_sma[my_list_no].size() - 1).getMax() == -1) {
				my_sma[my_list_no].get(my_sma[my_list_no].size() - 1).setMax(0); // daca
																					// precedentul
																					// tot
																					// minim
																					// il
																					// setam
																					// cu
																					// 0
																					// pe
																					// precedentul

			} else {
				// MAX_spike[my_list_no] =
				// my_sma[my_list_no].get(my_sma[my_list_no].size() -
				// 1).getVal(); //daca nu asta e un alt extrem

			}
		} else if (variatie < 0) {
			max = 1;
			now_trend[my_list_no] = 1;
			if (my_sma[my_list_no].get(my_sma[my_list_no].size() - 1).getMax() == 1) {
				my_sma[my_list_no].get(my_sma[my_list_no].size() - 1).setMax(0); // daca
																					// precedentul
																					// tot
																					// maxim
																					// il
																					// setam
																					// cu
																					// 0
																					// pe
																					// precedentul

			} else {
				// MAX_spike[my_list_no] =
				// my_sma[my_list_no].get(my_sma[my_list_no].size() -
				// 1).getVal(); //daca nu asta e un alt extrem
			}
		}

		return max;
	}

	public void getData(int my_list_no, String CSVfile) {
		final String ADDRESS_FILE = CSVfile;
		CSVReader reader;
		try {
			reader = new CSVReader(new FileReader(ADDRESS_FILE));

			String[] nextLine;
			if ((nextLine = reader.readNext()) != null) {
				int numLines = nextLine.length;
				// System.out.println("Number of Data Items: " + numLines);
				Calendar c = Calendar.getInstance();

				c.set(new Integer(nextLine[0].substring(0, 4)).intValue(),
						new Integer(nextLine[0].substring(5, 7)).intValue(),
						new Integer(nextLine[0].substring(8, 10)).intValue(),
						new Integer(nextLine[1].substring(0, 2)).intValue(),
						new Integer(nextLine[1].substring(3, 5)).intValue());
				MAX_spike[my_list_no] = new Double(now_sma1.compute(new Double(
						nextLine[2]))).doubleValue();

			}
			while ((nextLine = reader.readNext()) != null) {
				int numLines = nextLine.length;
				// System.out.println("Number of Data Items: " + numLines);
				Calendar c = Calendar.getInstance();

				c.set(new Integer(nextLine[0].substring(0, 4)).intValue(),
						new Integer(nextLine[0].substring(5, 7)).intValue(),
						new Integer(nextLine[0].substring(8, 10)).intValue(),
						new Integer(nextLine[1].substring(0, 2)).intValue(),
						new Integer(nextLine[1].substring(3, 5)).intValue());
				double now_val_sma = new Double(now_sma1.compute(new Double(
						nextLine[2]))).doubleValue();

				my_sma[my_list_no].add(new indicator(now_val_sma, getMinMax(
						my_list_no, now_val_sma), now_trend[my_list_no],c.getTimeInMillis()));
				// / my_sma2[my_list_no].add(now_sma2.compute(new
				// Double(nextLine[2])));
				candle new_candle = new candle(c.getTimeInMillis(), new Double(
						nextLine[2]).doubleValue(),
						new Double(nextLine[3]).doubleValue(), new Double(
								nextLine[4]).doubleValue(), new Double(
								nextLine[5]).doubleValue(), new Integer(
								nextLine[6]).intValue(), 0);
				my_period[my_list_no].add(new_candle);

				// System.out.println("     nextLine[" + i + "]:  " +
				// nextLine[i]);

			}
			System.out.println("   " + my_period[my_list_no].size());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void newcandle(int my_list_no, long time, double now_val_sma, double open, double high, double low, double close, int volume) {
		if (my_sma[my_list_no].get(0).getVal() == 0) {
				my_sma[my_list_no].get(0).setVal(now_val_sma);
				MAX_spike[my_list_no] = now_val_sma;
				last_time[my_list_no] = time;
	    }
		
			last_time[my_list_no] = time;
			
			if (config.getSMA2() > 0) {
				my_sma[my_list_no].add(new indicator(now_val_sma, getMinMax(
						my_list_no, now_val_sma), now_trend[my_list_no],time));

				// / my_sma2[my_list_no].add(now_sma2.compute(new
				// Double(nextLine[2])));
				candle new_candle = new candle(time, open, high, low, close,
						volume, 0);
				my_period[my_list_no].add(new_candle);
			}
			else{
				now_patt_v2.newVal(my_list_no, now_val_sma, time);
			}
	

	}

	private static SimpleConfig getConfig() {
		if (config == null) {
			config = new SimpleConfig(SimpleConfig.RESOURCE_NAME);

			ConfigValidationResult configResult = config
					.validateConfiguration();

			if (configResult.thereAreErrors()) {
				System.out.println("Errors in configuration");

				for (Iterator<?> iter = configResult.getErrors().iterator(); iter
						.hasNext();) {
					System.out.println(" > " + iter.next());
				}

				System.exit(1);
			}

			if (configResult.thereAreUnusedProperties()) {
				System.out.println("Unused properties");

				for (Iterator<?> iter = configResult.getUnusedProperties()
						.iterator(); iter.hasNext();) {
					System.out.println(" > " + iter.next());
				}
			}
		}

		return config;
	}

	public void savePattern() {
		// genereaza patternurile
		for (int p = my_sma.length - 1; p > 0; p--) {

			double val = 0;

			int[] last_index = new int[config.getPeriod().length];
			for (int i = 0; i < config.getPeriod().length; i++) {

				last_index[i] = 0;

			}
			int max_patt = 0;
			int max = 0;
			int trend = 0;
			indicator last_extrem = new indicator(0, 0, 0,0);
			long last_time = 0;
			long time = 0;

			last_extrem.setMax(my_sma[p].get(0).getMax());
			last_extrem.setTrend(my_sma[p].get(0).getTrend());
			last_extrem.setVal(my_sma[p].get(0).getVal());
			last_time = my_period[p].get(0).getTime();

			for (int i = 1; i < my_sma[p].size(); i++) {

				val = my_sma[p].get(i).getVal();
				max = my_sma[p].get(i).getMax();
				trend = my_sma[p].get(i).getTrend();

				if (my_sma[p].get(i).getMax() != 0) {

					time = my_period[p].get(i).getTime();
					pattern new_patt = new pattern(
							(int) ((last_extrem.getVal() - val) * 100000));
					for (int j = last_index[p - 1]; j < my_sma[p - 1].size(); j++) {

						if (my_period[p - 1].get(j).getTime() < time) {
							int dpip = (int) ((my_sma[p - 1].get(j).getVal() - last_extrem
									.getVal()) * 100000);
							new_patt.addPunct(new punct((int) (my_period[p - 1]
									.get(j).getTime() - last_time), dpip));
						} else {

							last_index[p - 1] = j - 1;
							break;
						}

					}
					my_pattern[p - 1].add(new_patt);
					if (new_patt.sizePatt() > max_patt)
						max_patt = new_patt.sizePatt();
					last_extrem.setMax(max);
					last_extrem.setTrend(trend);
					last_extrem.setVal(val);
					last_time = my_period[p].get(i).getTime();
				}
			}
			max_patts[p - 1] = max_patt;
			System.out.println("lungime maxima patt: " + max_patt);
			System.out.println("cate  patt: " + my_pattern[p - 1].size());
		}

	}

	public void patternRemove_0() {
		for (int p = 0; p < my_pattern.length; p++) {
			for (int i = 0; i < my_pattern[p].size(); i++) {

				// System.out.println("cate  patt: " + i
				// +" : "+my_pattern[p].size());

				for (int j = 0; j < my_pattern[p].get(i).sizePatt(); j++) {
					if (my_pattern[p].get(i).getPunct(j).getDpip() == 0) {

						my_pattern[p].get(i).removePunct(j);
						j--;
					}

				}
				if (my_pattern[p].get(i).sizePatt() < config.getComparePoints() / 10) {

					my_pattern[p].remove(i);

					i--;
				}

			}

		}
	}

	public void patternRemove_eqll() {
		for (int p = 0; p < my_pattern.length; p++) {
			for (int i = 0; i < my_pattern[p].size(); i++) {

				// System.out.println("cate  patt: " + i
				// +" : "+my_pattern[p].size());

				for (int j = 0; j < my_pattern[p].get(i).sizePatt(); j++) 
					for (int w = j+1; w < my_pattern[p].get(i).sizePatt(); w++){
					if (my_pattern[p].get(i).getPunct(j).getDpip() == my_pattern[p].get(i).getPunct(w).getDpip()) {

						my_pattern[p].get(i).removePunct(w);
						w--;
					}

				}
				if (my_pattern[p].get(i).sizePatt() < config.getComparePoints() / 10) {

					my_pattern[p].remove(i);

					i--;
				}

			}

		}
	}
	public void patternRemove_equal() {
		for (int p = 0; p < my_pattern.length; p++) {
			for (int i = 0; i < my_pattern[p].size(); i++) {
				boolean count_eq = false;
				for (int h = i + 1; h < my_pattern[p].size(); h++) {
					if (my_pattern[p].get(i).eq(my_pattern[p].get(h))) {
						if (!(my_pattern[p].get(i)
								.eqTrend(my_pattern[p].get(h))))
							count_eq = true;
						my_pattern[p].remove(h);

						h--;
					}
				}
				if (count_eq) {
					my_pattern[p].remove(i);
					i--;
				}
			}

		}
	}

	public <indicator> void saveListIndicator(ArrayList<indicator> list, int i) {
		File f = new File(config.getPathOut(), i + this.Instrument + "indi.ind");
		

			try {
				FileOutputStream fos = new FileOutputStream(f);
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				oos.writeObject(list);
				fos.close();
			} catch (IOException ioe) {
			}

		
	}

	public <indicator> void saveListIndicatorSQL0(ArrayList<indicator> list,
			int i) {
		wee T = new wee();
		boolean error = true;
		System.out.println("LIB version: " + SQLite.Database.version());
		SQLite.Database db = new SQLite.Database();
		try {

			db.open("c:\\wamp\\www\\db_ind1.db", 0666);
			System.out.println("DB version: " + db.dbversion());
			db.busy_timeout(1000);
			db.busy_handler(null);
			db.trace(T);
			db.profile(T);
			T.do_exec(
					db,
					"CREATE TABLE sma"
							+ this.Instrument
							+ i
							+ "(timp INTEGER NOT NULL, val REAL NOT NULL, max INTEGER NOT NULL, trend INTEGER NOT NULL)");
			
				Stmt ins = T.prep_ins(db, "insert into sma" + this.Instrument
						+ i + "(timp , val , max , trend)"
						+ " VALUES(:one,:two,:three,:four)");
				int cj=0;
				for (int j = 1; j < my_sma[i].size(); j++) {

					double val = my_sma[i].get(j).getVal();
					int max = my_sma[i].get(j).getMax();
					int trend = my_sma[i].get(j).getTrend();
					long time = my_period[i].get(j).getTime();
				

				T.do_ins(ins, time, val, max, trend);
			
			}
ins.close();
			error = false;
		} catch (java.lang.Exception e) {
			System.err.println("error: " + e);
			e.printStackTrace();
		} finally {
			try {
				System.err.println("cleaning up ...");
				try {
					T.do_exec(db, "drop table TEST3");
					T.do_exec(db, "drop table B");
				} catch (SQLite.Exception e) {
				}
				db.close();
			} catch (java.lang.Exception e) {
				System.err.println("error: " + e);
				error = true;
			} finally {
				System.err.println("done.");
			}
		}
		if (error) {
			System.exit(1);
		}

	}
	public <indicator> void saveListIndicatorSQL1(ArrayList<indicator> list,
			int i) {
		wee T = new wee();
		boolean error = true;
		System.out.println("LIB version: " + SQLite.Database.version());
		SQLite.Database db = new SQLite.Database();
		try {

			db.open("c:\\wamp\\www\\db_ind2.db", 0666);
			System.out.println("DB version: " + db.dbversion());
			db.busy_timeout(1000);
			db.busy_handler(null);
			db.trace(T);
			db.profile(T);
			T.do_exec(
					db,
					"CREATE TABLE sma"
							+ this.Instrument
							+ i
							+ "(timp INTEGER NOT NULL, val REAL NOT NULL, max INTEGER NOT NULL, trend INTEGER NOT NULL)");
			
				String insert ="insert into sma" + this.Instrument+ i + "\n   ";
				String Stm_ins="";
				int cj=0;
				for (int j = 1; j < my_sma[i].size(); j++) {
					double val = my_sma[i].get(j).getVal();
					int max = my_sma[i].get(j).getMax();
					int trend = my_sma[i].get(j).getTrend();
					long time = my_period[i].get(j).getTime();
					if (cj==0){
						Stm_ins="select "+time+" as timp ,"+val+" as val ,"+max+" as max ,"+trend+" as trend \n  ";
						
					}else if (cj<489){
						Stm_ins+="union select "+time+" ,"+val+"  ,"+max+"  ,"+trend+"\n  ";
					}
					else {
						cj=-1;
					//	System.out.println("SQL: " + insert+Stm_ins);
						T.do_exec(db,insert+Stm_ins);
					}
cj++;
				
			
			}

			error = false;
		} catch (java.lang.Exception e) {
			System.err.println("error: " + e);
			e.printStackTrace();
		} finally {
			try {
				
				db.close();
			} catch (java.lang.Exception e) {
				System.err.println("error: " + e);
				error = true;
			} finally {
				System.err.println("done.");
			}
		}
		if (error) {
			System.exit(1);
		}

	}
	public <indicator> void saveListIndicatorSQL(ArrayList<indicator> list, int i) {
		wee T = new wee();
		boolean error = true;
		System.out.println("LIB version: " + SQLite.Database.version());
		SQLite.Database db = new SQLite.Database();
		try {

			db.open("c:\\wamp\\www\\db_ind2.db", 0666);
			System.out.println("DB version: " + db.dbversion());
			db.busy_timeout(1000);
			db.busy_handler(null);
			db.trace(T);
			db.profile(T);
			T.do_exec(
					db,
					"CREATE TABLE cand"
							+ this.Instrument
							+ i
							+ "(timp INTEGER NOT NULL, open REAL NOT NULL, high REAL NOT NULL,  close REAL NOT NULL, low REAL NOT NULL, volume INTEGER NOT NULL, max INTEGER NOT NULL)");
			
				String insert ="insert into cand" + this.Instrument+ i + "\n   ";
				String Stm_ins="";
				int cj=0;
				for (int j = 1; j < my_sma[i].size(); j++) {
					double open = my_period[i].get(j).getOpen();
					double high = my_period[i].get(j).getHigh();
					double close= my_period[i].get(j).getClose();
					double low=my_period[i].get(j).getClose();
					int volume=my_period[i].get(j).getVolume();
					long time = my_period[i].get(j).getTime();
					int max=my_period[i].get(j).getMax();
					if (cj==0){
						Stm_ins="select "+time+" as timp ,"+open+" as open ,"+high+" as high ,"+close+" as close ,"+low+" as low ,"+volume+" as volume ,"+max+" as max \n  ";
						
					}else if (cj<489){
						Stm_ins+="union select  "+time+"  ,"+open+"  ,"+high+"  ,"+close+" ,"+low+" ,"+volume+" ,"+max+"\n  ";
					}
					else {
						cj=-1;
					//	System.out.println("SQL: " + insert+Stm_ins);
						T.do_exec(db,insert+Stm_ins);
					}
cj++;
				
			
			}

			error = false;
		} catch (java.lang.Exception e) {
			System.err.println("error: " + e);
			e.printStackTrace();
		} finally {
			try {
				
				db.close();
			} catch (java.lang.Exception e) {
				System.err.println("error: " + e);
				error = true;
			} finally {
				System.err.println("done.");
			}
		}
		if (error) {
			System.exit(1);
		}

	}

	public <candle> void saveListCandle(ArrayList<candle> list, int i) {
		File f = new File(config.getPathOut(), i + this.Instrument + "cand.cnd");
		

			try {
				FileOutputStream fos = new FileOutputStream(f);
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				oos.writeObject(list);
				fos.close();
			} catch (IOException ioe) {
				System.out.println(ioe.toString());
			}

		
	}

	
	@SuppressWarnings("unchecked")
	public ArrayList<indicator> getListIndicator(int i) {
		ArrayList<indicator> list = null;
		File f = new File(config.getPathOut() + i + "sma.ind");
		if (f.exists()) {

			try {
				FileInputStream fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				try {
					list = (ArrayList<indicator>) ois.readObject(); // [I]bad
																	// monkey[/I]
				} catch (ClassNotFoundException cnfe) {
					cnfe.printStackTrace();
				}
				fis.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}

		}
		return list;
	}

	public void saveListPatterns() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			saveListPattern(my_pattern[i], i);

		}
	}
	public void saveListIndicators() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			saveListIndicator(my_sma[i], i);

		}
	}
	
	public void saveListIndicatorsToSql() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			saveListIndicatorSQL(my_sma[i], i);

		}
	}
	public void saveListCandles() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			saveListCandle(my_period[i], i);

		}
	}
	public void getListPatterns() {
		for (int i = 0; i < config.getPeriod().length; i++) {

			getListPattern(i);

		}
	}
	public void getListIndicators(String Instru) {
		for (int i = 0; i < config.getPeriod().length; i++) {

			getListIndici(Instru, i);

		}
	}
	public void getListCandles(String Instru) {
		for (int i = 0; i < config.getPeriod().length; i++) {

			getListCandle(Instru, i);

		}
	}

	public void getListPatterns(String Instru) {
		for (int i = 0; i < config.getPeriod().length; i++) {

			getListPattern(Instru, i);

		}
	}

	public <pattern> void saveListPattern(ArrayList<pattern> list, int i) {
		File f = new File(config.getPathOut(), i + this.Instrument + "patt.pat");
		// if (f.exists()) {

		try {
			FileOutputStream fos = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(list);
			fos.close();
		} catch (IOException ioe) {
		}

		// }
	}

	@SuppressWarnings("unchecked")
	public ArrayList<pattern> getListPattern(int i) {
		ArrayList<pattern> list = null;
		File dir = new File(config.getPathOut());

		String[] children = dir.list();
		if (children == null) {
			// Either dir does not exist or is not a directory
		} else {
			for (int j = 0; j < children.length; j++) {
				// Get filename of file or directory
				String filename = children[j];
				if ((filename.length() > 15)
						&& (filename.endsWith("patt.pat"))
						&& (new Integer(filename.substring(0, 1)).intValue() == i)) {
					File f = new File(config.getPathOut(), filename);
					if (f.exists()) {

						try {
							FileInputStream fis = new FileInputStream(f);
							ObjectInputStream ois = new ObjectInputStream(fis);
							try {
								list = (ArrayList<pattern>) ois.readObject(); // [I]bad
																				// monkey[/I]
							} catch (ClassNotFoundException cnfe) {
								cnfe.printStackTrace();
							}
							fis.close();
							my_pattern[i].addAll(list);
						} catch (IOException ioe) {
							ioe.printStackTrace();
						}
					}
				}
			}
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<pattern> getListPattern(String Instru, int i) {
		ArrayList<pattern> list = null;

		// Get filename of file or directory

		File f = new File(config.getPathOut(), i + Instru + "patt.pat");
		if (f.exists()) {

			try {
				FileInputStream fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				try {
					list = (ArrayList<pattern>) ois.readObject(); // [I]bad
																	// monkey[/I]
				} catch (ClassNotFoundException cnfe) {
					cnfe.printStackTrace();
				}
				fis.close();
				my_pattern[i].addAll(list);
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		return list;
	}
	@SuppressWarnings("unchecked")
	public ArrayList<indicator> getListIndici(String Instru, int i) {
		ArrayList<indicator> list = null;

		// Get filename of file or directory

		File f = new File(config.getPathOut(), i + Instru + "indi.ind");
		if (f.exists()) {

			try {
				FileInputStream fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				try {
					list = (ArrayList<indicator>) ois.readObject(); // [I]bad
																	// monkey[/I]
				} catch (ClassNotFoundException cnfe) {
					cnfe.printStackTrace();
				}
				fis.close();
				my_sma[i].addAll(list);
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		return list;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<candle> getListCandle(String Instru, int i) {
		ArrayList<candle> list = null;

		// Get filename of file or directory

		File f = new File(config.getPathOut(), i + Instru + "cand.cnd");
		if (f.exists()) {

			try {
				FileInputStream fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				try {
					list = (ArrayList<candle>) ois.readObject(); // [I]bad
																	// monkey[/I]
				} catch (ClassNotFoundException cnfe) {
					cnfe.printStackTrace();
				}
				fis.close();
				my_period[i].addAll(list);
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		return list;
	}
	
	
	@SuppressWarnings("static-access")
	public void getCurrentPatt_learn_v1() {
		long now_time = 0;

		double val = 0;

		int[] last_index = new int[config.getPeriod().length];
		long[] last_time = new long[config.getPeriod().length];
		indicator[] last_extrem = new indicator[config.getPeriod().length];
		for (int i = 0; i < config.getPeriod().length; i++) {

			last_index[i] = 1;
			last_extrem[i] = new indicator(0, 0, 0,0);
			last_extrem[i].setVal(my_sma[i].get(0).getVal());
			last_time[i] = my_period[i].get(0).getTime();
			now_patt[i].addPunct(new punct(0, 0));
		}

		int max = 0;
		int trend = 0;

		long time = 0;
		my_plot.goPlot();

		// luam la rand toti indicii din cea mai mica M
		// in fuctie de timp incrementam indicele pe M superioare
		// adaugam in pattern punctul fata de punctul anterior +punctul anterior
		//
		int win_profit = 0;
		int lost_profit = 0;
		int no_orders = 0;
		boolean current_order = false;
		for (int i = 1; i < my_sma[0].size(); i++) {

			val = my_sma[0].get(i).getVal();

			now_time = my_period[0].get(i).getTime();

			for (int k = 0; k < config.getPeriod().length - 1; k++) {
				if ((now_time < my_period[k].get(last_index[k]).getTime())
						|| (k == 0)) {
					now_patt[k].addPunctMaxSize(
							new punct(now_patt[k].getPunct(
									now_patt[k].sizePatt() - 1).getDtimp()
									+ (int) (now_time - last_time[k]),
									now_patt[k].getPunct(
											now_patt[k].sizePatt() - 1)
											.getDpip()
											+ (int) ((val - last_extrem[k]
													.getVal()) * 100000)),
							max_patts[k], new indicator(0,0,0,0));

					last_extrem[k]
							.setVal(my_sma[k].get(last_index[k]).getVal());
					if (last_index[k] < my_sma[k].size() - 2)
						last_index[k]++;

					if ((k == 0) && (now_patt[0].sizePatt() > 2)) {
						my_plot.getCollector()
								.getPunct()
								.setDtimp(
										now_patt[0].getPunct(
												now_patt[0].sizePatt() - 1)
												.getDtimp());
						my_plot.getCollector()
								.getPunct()
								.setDpip(
										now_patt[0].getPunct(
												now_patt[0].sizePatt() - 1)
												.getDpip());
					}

				}
				for (int w = 0; w < my_orders.size(); w++) {
					int delta = (int) ((my_period[0].get(i).getOpen() - my_orders
							.get(w).getIn()) * 100000);
					int takeP = my_orders.get(w).getTp();
					int sellL = my_orders.get(w).getSl();

					if (((delta * takeP) > 0)
							&& ((delta * delta) >= (takeP * takeP))) {
						win_profit += (int) ((Math.sqrt(delta * delta)));
						// System.out.println("WWIN ###########close order! profit"
						// +(int)( (Math.sqrt(delta*delta))));
						my_orders.remove(w);
						current_order = false;
						w--;
					} else if (((delta * takeP) < 0)
							&& ((delta * delta) >= (sellL * sellL))) {
						lost_profit = (int) ((Math.sqrt(delta * delta)));
						// System.out.println("LOST ###########close order! profit"
						// +(int)( (Math.sqrt(delta*delta))));
						my_orders.remove(w);
						current_order = false;
						w--;

					}

				}

				int no_eq = 0;
				int eq_profit = 0;

				for (int w = 0; w < my_pattern[k].size(); w++) {
					if (now_patt[k].eq(my_pattern[k].get(w))) {
						if (no_eq > 0) {
							if (eq_profit * my_pattern[k].get(w).getAmpli() < 0) {
								no_eq = 0;
								break;
							} else {
								if (my_pattern[k].get(w).getAmpli()
										* my_pattern[k].get(w).getAmpli() > eq_profit
										* eq_profit)
									eq_profit = my_pattern[k].get(w).getAmpli();
							}
						} else {
							no_eq++;
							eq_profit = my_pattern[k].get(w).getAmpli();
						}

					}
				}

				// daca s-a asemanta cu un pattern sau mai multe si toate au
				// fost de acelasi T

				if ((no_eq > 0) && (!current_order)) {
					my_orders.add(new order(now_time, my_period[0].get(i)
							.getOpen(), eq_profit, config.getSLPoints()));
					// System.out.println("new order! total orders"
					// +my_orders.size());
					no_orders++;
					current_order = true;
				}

			}

			last_time[0] = now_time;

		}
		System.out.println("profit : " + win_profit);
		System.out.println("pierdere : " + lost_profit);
		System.out.println("profit total: " + (win_profit - lost_profit));
		System.out.println("no ordine : " + no_orders);
	}

	@SuppressWarnings("static-access")
	public void startCurrentPatt_v2() {

		long[] last_time = new long[config.getPeriod().length];
		indicator[] last_extrem = new indicator[config.getPeriod().length];
		for (int i = 0; i < config.getPeriod().length; i++) {

			last_extrem[i] = new indicator(0, 0, 0,0);
			last_extrem[i].setVal(my_sma[i].get(0).getVal());
			last_time[i] = my_period[i].get(0).getTime();
			now_patt[i].addPunct(new punct(0, 0));
		}
	}

	@SuppressWarnings("static-access")
	public void getCurrentPatt_learn_v2(ITick tick) {
		long now_time = 0;

		double val = 0;

		int[] last_index = new int[config.getPeriod().length];
		long[] last_time = new long[config.getPeriod().length];
		indicator[] last_extrem = new indicator[config.getPeriod().length];
		for (int i = 0; i < config.getPeriod().length; i++) {

			last_index[i] = 1;
			last_extrem[i] = new indicator(0, 0, 0,0);
			last_extrem[i].setVal(my_sma[i].get(0).getVal());
			last_time[i] = my_period[i].get(0).getTime();
			now_patt[i].addPunct(new punct(0, 0));
		}

		int max = 0;
		int trend = 0;

		long time = 0;
		my_plot.goPlot();

		// luam la rand toti indicii din cea mai mica M
		// in fuctie de timp incrementam indicele pe M superioare
		// adaugam in pattern punctul fata de punctul anterior +punctul anterior
		//
		int win_profit = 0;
		int lost_profit = 0;
		int no_orders = 0;
		boolean current_order = false;

		double valA = tick.getAsk();

		now_time = tick.getTime();

		for (int k = 0; k < config.getPeriod().length - 1; k++) {
			if ((now_time < my_period[k].get(last_index[k]).getTime())
					|| (k == 0)) {
				now_patt[k]
						.addPunctMaxSize(
								new punct(now_patt[k].getPunct(
										now_patt[k].sizePatt() - 1).getDtimp()
										+ (int) (now_time - last_time[k]),
										now_patt[k].getPunct(
												now_patt[k].sizePatt() - 1)
												.getDpip()
												+ (int) ((val - last_extrem[k]
														.getVal()) * 100000)),
								max_patts[k], new indicator(0,0,0,0));

				last_extrem[k].setVal(my_sma[k].get(last_index[k]).getVal());
				if (last_index[k] < my_sma[k].size() - 2)
					last_index[k]++;

				if ((k == 0) && (now_patt[0].sizePatt() > 2)) {
					my_plot.getCollector()
							.getPunct()
							.setDtimp(
									now_patt[0].getPunct(
											now_patt[0].sizePatt() - 1)
											.getDtimp());
					my_plot.getCollector()
							.getPunct()
							.setDpip(
									now_patt[0].getPunct(
											now_patt[0].sizePatt() - 1)
											.getDpip());
				}

			}
			for (int w = 0; w < my_orders.size(); w++) {
				int delta = (int) ((val - my_orders.get(w).getIn()) * 100000);
				int takeP = my_orders.get(w).getTp();
				int sellL = my_orders.get(w).getSl();

				if (((delta * takeP) > 0)
						&& ((delta * delta) >= (takeP * takeP))) {
					win_profit += (int) ((Math.sqrt(delta * delta)));
					// System.out.println("WWIN ###########close order! profit"
					// +(int)( (Math.sqrt(delta*delta))));
					my_orders.remove(w);
					current_order = false;
					w--;
				} else if (((delta * takeP) < 0)
						&& ((delta * delta) >= (sellL * sellL))) {
					lost_profit = (int) ((Math.sqrt(delta * delta)));
					// System.out.println("LOST ###########close order! profit"
					// +(int)( (Math.sqrt(delta*delta))));
					my_orders.remove(w);
					current_order = false;
					w--;

				}

			}

			int no_eq = 0;
			int eq_profit = 0;

			for (int w = 0; w < my_pattern[k].size(); w++) {
				if (now_patt[k].eq(my_pattern[k].get(w))) {
					if (no_eq > 0) {
						if (eq_profit * my_pattern[k].get(w).getAmpli() < 0) {
							no_eq = 0;
							break;
						} else {
							if (my_pattern[k].get(w).getAmpli()
									* my_pattern[k].get(w).getAmpli() > eq_profit
									* eq_profit)
								eq_profit = my_pattern[k].get(w).getAmpli();
						}
					} else {
						no_eq++;
						eq_profit = my_pattern[k].get(w).getAmpli();
					}

				}
			}

			// daca s-a asemanta cu un pattern sau mai multe si toate au
			// fost de acelasi T

			if ((no_eq > 0) && (!current_order)) {
				my_orders.add(new order(now_time, val, eq_profit, config
						.getSLPoints()));
				// System.out.println("new order! total orders"
				// +my_orders.size());
				no_orders++;
				current_order = true;
			}

		}

		last_time[0] = now_time;

		System.out.println("profit : " + win_profit);
		System.out.println("pierdere : " + lost_profit);
		System.out.println("profit total: " + (win_profit - lost_profit));
		System.out.println("no ordine : " + no_orders);
	}

	public int isGoodPatt() {
		for (int k = 0; k < config.getPeriod().length - 1; k++) {
			int no_eq = 0;
			int eq_profit = 0;

			for (int w = 0; w < my_pattern[k].size(); w++) {
				if (now_patt_v2.now_patt[k].eqShift(my_pattern[k].get(w))) {
					if (no_eq > 0) {
						if (eq_profit * my_pattern[k].get(w).getAmpli() < 0) {
							no_eq = 0;
							break;
						} else {
							if (my_pattern[k].get(w).getAmpli()
									* my_pattern[k].get(w).getAmpli() > eq_profit
									* eq_profit)
								eq_profit = my_pattern[k].get(w).getAmpli();
						}
					} else {
						no_eq++;
						eq_profit = my_pattern[k].get(w).getAmpli();
					}

				}
			}

			// daca s-a asemanta cu un pattern sau mai multe si toate au
			// fost de acelasi T

			if (no_eq > 0) {
				return eq_profit;
				// System.out.println("new order! total orders"
				// +my_orders.size());

			}
		}
		return 0;

	}

	public void pattmaxlen() {
	
		for (int i = 0; i < config.getPeriod().length-1; i++){
			int 	max=0;
		int med=0;
		for (int w = 0; w < my_pattern[i].size(); w++) {
				if( my_pattern[i].get(w).sizePatt()>max)max=my_pattern[i].get(w).sizePatt();
				med+=my_pattern[i].get(w).sizePatt();
			}
					
System.out.println("max patt: " + max + " med patt : "+med/my_pattern[i].size());
		}
	}

	public void pattsizee() {
		for (int i = 0; i < config.getPeriod().length; i++)
			System.out.println("cate  patt: " + i + " : "
					+ my_pattern[i].size());

	}
	public void indsizee() {
		for (int i = 0; i < config.getPeriod().length; i++)
			System.out.println("cate  patt: " + i + " : "
					+ my_sma[i].size());

	}
	public void candsizee() {
		for (int i = 0; i < config.getPeriod().length; i++)
			System.out.println("cate  patt: " + i + " : "
					+ my_period[i].size());

	}
	public void updateCurrentPatterns(double sma_nou) {
		System.out.println("updatecurrpat t :"+sma_nou);

	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		nextpattern my_try1 = new nextpattern();
		KKMultiServer myserver= new KKMultiServer(my_try1);
		myserver.start();
	/*	nextpattern my_try1 = new nextpattern();
		my_try1.setInstrument("GBP_USD");
		my_try1.getListIndicators(my_try1.Instrument);
		my_try1.getListCandles(my_try1.Instrument);
		// my_try1.savePattern();
		// my_try1.saveListIndicator(my_try1.my_sma[2], "2sma.dat");
		// my_try1.my_sma[0]=my_try1.getListIndicator( "2sma.dat");
		// my_try1.saveListPattern(my_try1.my_pattern[0], "2patt.dat");
		my_try1.indsizee();		my_try1.candsizee();
			
		my_try1.saveListIndicatorsToSql(); 
		// my_try1.patternRemove_0();

		// my_try1.patternRemove_equal();
	
		// my_try1.saveListPatterns();
		// my_try1.getCurrentPatt_learn_v1();
		// System.out.println("Press enter to return to menu");
		*/
	}

}
